package cn.buk.tms.flight.service;

import cn.buk.common.util.DateUtil;
import cn.buk.qms.service.BaseFlightOrderService;
import cn.buk.qms.service.FlightChangeOrderService;
import cn.buk.tms.entity.misc.EntDepartment;
import cn.buk.tms.entity.order.flight.FlightChangeOrder;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static cn.buk.common.JsonResult.STATUS_OK;
import static cn.buk.tms.common.constant.TmsConstant.FLIGHT_AUTO_TICKETING_NDC_CZ;
import static java.nio.charset.StandardCharsets.UTF_8;

@Service
public class AutoChangeServiceImpl extends BaseFlightOrderService implements AutoChangeService {

  public static final Logger logger = LogManager.getLogger(AutoChangeServiceImpl.class);

  @Autowired
  public AutoChangeServiceImpl(FlightChangeOrderService changeOrderService) {
    this.changeOrderService = changeOrderService;
  }

  private final FlightChangeOrderService changeOrderService;

  @Override
  public void checkFlightChangeOrder(final int enterpriseId, final String username) {
    //搜索改签单
    final Date startDate = DateUtil.addDays(DateUtil.getCurDate(), -10);
    List<FlightChangeOrder> changeOrders = changeOrderDao.searchWaiting(enterpriseId, startDate);

    if (changeOrders.isEmpty()) {
      return;
    }
    logger.info("waiting for change: {}", changeOrders.size());

    for (var changeOrder : changeOrders) {

      if (changeOrder.getSupplier() == null || changeOrder.getSupplier().getIsBsp() != FLIGHT_AUTO_TICKETING_NDC_CZ) {
        continue;
      }

      if (changeOrder.getCustomer() != null && changeOrder.getCustomer().getTestMode() == 1) {
        //测试模式的客户，不自动改签
        continue;
      }

      final String key = String.format(CZ_NDC_CHANGE_ORDER_KEY, enterpriseId, changeOrder.getChangeOrderNo());
      if (redisDao.exists(key)) {
        continue;
      }

      int retCode = execAutoChangeOrder(enterpriseId, username, changeOrder);
    }
  }

  /**
   * @return 错误代码：0 - 没有错误；
   * 其它数字 - 错误信息的代码
   */
  private int execAutoChangeOrder(final int enterpriseId, final String username, final FlightChangeOrder changeOrder) {
    //1. 是否已认领
    //1.1 未认领，则认领，并判断航司改签费是否准确; 不准确，并发出提醒消息
    //1.2 已认领，判断是否为当前用户，不是，则不处理
    if (StringUtils.isBlank(changeOrder.getTicketer())) {
      //准备认领后处理
      int retCode = changeOrderDao.processFlightChangeOrder(enterpriseId, username, changeOrder.getId());
      if (retCode != 1) {
        doSendAlert(enterpriseId, "改签单" + changeOrder.getChangeOrderNo() + "认领失败 by " + username, "Dai", 0);
        return 1;
      }

      //TODO 校验航司改签费是否相符 yfdai 2021-09-30
    } else if (!username.equalsIgnoreCase(changeOrder.getTicketer())) {
      return 2;
    }

    if (StringUtils.isBlank(changeOrder.getExternalOrderNo())) {
      var jr = changeOrderService.createNdcOrderChange(enterpriseId, username, changeOrder.getId());
      if (!STATUS_OK.equalsIgnoreCase(jr.getStatus())) {
        //创建失败
        var remark = "改签单" + changeOrder.getChangeOrderNo() + "提交失败 by " + username + ": " + jr.getErrmsg();
        doSendAlert(enterpriseId, remark, null, EntDepartment.DEPT_TICKETING);

        changeOrderDao.appendFlightChangeOrderLog(enterpriseId, changeOrder.getId(), username, remark);

        final String key = String.format(CZ_NDC_CHANGE_ORDER_KEY, enterpriseId, changeOrder.getChangeOrderNo());
        redisDao.setAndExpire(key, remark.getBytes(UTF_8), 60L * 60 * 24);

        return 1;
      }
    } else {
      //同步退票单状态
      changeOrderService.syncNdcOrderChangeInfo(enterpriseId, username, changeOrder.getId());
    }

    return 0;

  }
}
